import { HTTP } from '../utils/http'
import { default as ProductUtils } from '../utils/product'
import { User as UserUtils } from '../utils/user'

const productUtils = new ProductUtils()
const userUtils = new UserUtils()

class CreditService extends HTTP {

    /**
     * 查询用户的信用信息
     */
    getUserCredit() {
        const userInfo = userUtils.getUserFromLocalStorage()
        const { token } = userInfo

        if (userUtils.isLoginValid()) {
            return this.request({
                url: `/mini/apply/credit`,
                header: {
                    Authorization: userUtils.getBearToken(token),
                }
            })
        }

        const empty = new Promise((resolve, reject) => {
            resolve({})
        })
        return empty
    }

    /**
     * 更新用户信用信息
     * @param {*} credit 信用信息对象
     */
    updateUserCredit(credit) {
        const userInfo = userUtils.getUserFromLocalStorage()
        const { token } = userInfo
        const creditCopy = Object.assign({}, credit)
        if (Array.isArray(creditCopy.city_code) && creditCopy.city_code.length >= 2) {
            creditCopy.city_code = creditCopy.city_code[1]
            // 删除无用的字段
            delete creditCopy.city_index
            delete creditCopy.city_name
        }

        if (userUtils.isLoginValid()) {
            return this.request({
                url: `/mini/apply/credit`,
                method: 'POST',
                data: creditCopy,
                header: {
                    Authorization: userUtils.getBearToken(token),
                }
            })
        }

        const empty = new Promise((resolve, reject) => {
            resolve({})
        })
        return empty
    }
}

export default CreditService